<?php

namespace App\Clients\MeiTuan;

use App\Clients\BaseClient;
use App\Models\Account;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Model;
use Psr\Http\Message\ResponseInterface;

abstract class MeiTuanClient extends BaseClient
{
    protected Model $account;

    /**
     * @throws Exception
     */
    public function __construct(Model $account)
    {
        parent::__construct();
        if(!($account instanceof Account)){
            $cookies = $account->account->cookies;
            $merchantNo = $account->merchant_no;
            $this->account = $account->account;
            $this->account->cookies = $this->cookieByMerchantNo($cookies,$merchantNo);
        }else{
            $this->account = $account;
        }
        if($this->account->login_status != 1)  throw new Exception("美团掉线了");

    }

    protected function cookieByMerchantNo($cookies,$merchantNo): array|string|null
    {
        return preg_replace('/merchantNo=\d+/', 'merchantNo='.$merchantNo, $cookies);
    }

    abstract public function execute($queryData);

    public function headers($other = []): array
    {
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "Referer"=>"https://pos.meituan.com/",
            "Cookie"=>$this->account->cookies,
            "model"=>"chrome",
            "Appcode"=>"49",
        ];
        return array_merge($headers,$other);
    }


    /**
     * @throws Exception
     */
    protected function isLogout(ResponseInterface $response){
        $content = $response->getBody()->getContents();
        if(str_contains($content,"登录失败，请重新登录")){
            $this->account->login_status = 0;
            $this->account->save();
            throw new Exception("美团掉线了");
        }
        $content = json_decode($content,true);
        if((
            !empty($content["code"]) && $content["code"] == 14101
        ) || (
                !empty($content["code"]) && $content["code"] == 401
            ) || (
                !empty($content["message"]) && $content["message"] == "登录失败，请重新登录"
            )){
            $this->account->login_status = 0;
            $this->account->save();
            throw new Exception("美团掉线了");
        }
        return $content;
    }

    /**
     * 初步处理数据
     * @return void
     */
    public function handleData(): void
    {
        try{
            $this->contents = $this->contents["data"];
        }catch(Exception $e){
            var_dump($this->contents);
            throw $e;
        }
    }

    public function contents(){
        return $this->contents;
    }

    /**
     * @throws GuzzleException
     */
    public function post($url, $postData): static
    {
        $headers = $this->headers();
        $response = $this->postData($url,$postData,$headers);
        $this->contents = $this->isLogout($response);
        $this->handleData();
        return $this;
    }

    /**
     * @throws GuzzleException
     */
    public function get($url, $postData): static
    {
        $headers = $this->headers();
        $response = $this->getData($url,$postData,$headers);
        $this->contents = $this->isLogout($response);
        $this->handleData();
        return $this;
    }
}
